package com.mofei.mall04_fileupload.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * 附件文件配置
 */
@Configuration
public class PathConfig implements WebMvcConfigurer {
    public static String attPaht = "";

    static {
        try { // 忽略mvn package test时的异常
            ApplicationHome h = new ApplicationHome(PathConfig.class);
            File jarF = h.getSource();
            attPaht = jarF.getParentFile().toString();
            if (attPaht.endsWith(File.separator + "target")) {
                attPaht = attPaht.substring(0, attPaht.lastIndexOf(File.separator + "target"));
            }
        } catch (Exception ignored) {
        }
    }

    @Value("${ATTACHMENT:}")
    private String path;

    /*配置模板资源路径*/
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (path == null || "".equals(path.replaceAll("\\s", "").replaceAll("\n", ""))) {
            registry.addResourceHandler("/ATTACHMENT/**")
                    .addResourceLocations("file:" + attPaht + "/ATTACHMENT/");
        }
    }
}
